package lzupdater.properties;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import lzupdater.locale.LocalizedString;
import lzupdater.log.Logger;
import lzupdater.log.LoggerLevel;
import lzupdater.properties.PropertyElement.HashMapProperty;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * 
 * @author Fraskor
 */
public class PropertiesManager {

	private final static LocalizedString fileNotFound = new LocalizedString(
			"The property file '%s' could not be found !");
	private final static LocalizedString loadingDone = new LocalizedString(
			"Properties loading done");
	private final static LocalizedString startLoading = new LocalizedString(
			"Start loading properties from '%s'");
	private final static LocalizedString ioExceptionReading = new LocalizedString(
			"IOException occured while reading -> %s");
	private final static LocalizedString ioExceptionSaving = new LocalizedString(
			"IOException occured while saving -> %s");
	private final static LocalizedString saveFile = new LocalizedString(
			"Start saving preferences to '%s'");
	private final static LocalizedString savingDone = new LocalizedString(
			"preferences saved");

	private PropertiesManager() {
	}

	/**
	 * load the property file
	 */
	public static HashMapProperty load(String propertyFile, Logger logger) {
		logger.debug(startLoading.useAsFormater(propertyFile));

		HashMapProperty root = PropertyElement.makeHashMapProperty();
		File f = new File(propertyFile);
		BufferedReader b;

		try {
			b = new BufferedReader(new FileReader(f));
		} catch (FileNotFoundException e) {
			logger.warning(fileNotFound.useAsFormater(propertyFile));
			return root;
		}

		String line = null;
		int lineNumber = 0;
		try {
			while ((line = b.readLine()) != null) {
				lineNumber++;
				int idx = line.indexOf('=');
				if (idx == -1 || line.trim().startsWith("#"))
					continue;

				String k = line.substring(0, idx - 1).trim();
				String v = line.substring(idx + 1).trim();

				logger.format(LoggerLevel.DEBUG,
						"(line :%03d) path='%s'  value='%s'", lineNumber, k, v);
				root.addProperty(k, v);
			}
			b.close();
		} catch (IOException e) {
			logger.debug(ioExceptionReading.useAsFormater(propertyFile));
			for (StackTraceElement s : e.getStackTrace()) {
				logger.debug(s.toString());
			}
		}

		logger.debug(loadingDone);
		return root;
	}

	/**
	 * @param header
	 * @throws IOException
	 */
	public static void save(String header, HashMapProperty root,
			String propertyFile, Logger logger) {
		logger.debug(saveFile.useAsFormater(propertyFile));
		try {
			BufferedWriter b = new BufferedWriter(new FileWriter(propertyFile));
			ArrayList<String> tmp = root.toString(null);

			if (header.trim().startsWith("#")) {
				b.write(header);
			} else {
				b.write(String.format("# %s", header));
			}
			b.newLine();

			for (String line : tmp) {
				b.write(String.format("%s", line));
				b.newLine();
			}
			b.close();
		} catch (IOException e) {
			logger.debug(ioExceptionSaving.useAsFormater(propertyFile));
			for (StackTraceElement s : e.getStackTrace()) {
				logger.debug(s.toString());
			}
		}
		logger.debug(savingDone);
	}

}
